<template>
  <a-drawer
      :visible="visible"
      title="意向客户明细"
      :width="$store.getters.isMobile ? '100%' : 1050"
      @close="onClose"
      :body-style="{
      boxSizing: 'border-box',
      overflow: 'auto',
    }"
      :destroyOnClose="true"
      :scroll="{
      x: 'max-content',
    }"
  >
    <a-table
        :columns="columns"
        :dataSource="tableData"
        bordered
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        :scroll="{ x: 'max-content' }"
    >
      <template #title>
        <div class="flex justify-between header-clue">
          <div class="flex-1">
            <a-form layout="vertical">
              <a-row :gutter="8" :wrap="true">
                <a-col :span="$store.getters.isMobile ? 12 : 6">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索联系人名称"
                        v-model:value="searchParams.name"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 12 : 6">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索联系人电话"
                        v-model:value="searchParams.tel"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 12 : 6">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索公司名称"
                        v-model:value="searchParams.company"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 12 : 6">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        :allowClear="true"
                        placeholder="请选择意向项目"
                        v-model:value="searchParams.village_id"
                        :options="villageOptions"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 12 : 6">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        placeholder="请选择客户状态"
                        :allowClear="true"
                        v-model:value="searchParams.status"
                        :options="customerStatusOptions"
                    >
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :span="$store.getters.isMobile ? 12 : 6">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        placeholder="请选择客户渠道"
                        :allowClear="true"
                        v-model:value="searchParams.channel_id"
                        :options="customerChannelOptions"
                    >
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :span="$store.getters.isMobile ? 12 : 6">
                  <a-form-item>
                    <a-range-picker
                        class="w-100p"
                        v-model:value="searchParams.created_time"
                        :value-format="dateFormatStr"
                        @change="handleRangePickerChange"
                    />
                  </a-form-item>
                </a-col>

                <a-col :span="$store.getters.isMobile ? 12 : 6">
                  <a-form-item label="">
                    <a-space>
                      <a-button @click="reset">重置</a-button>
                      <a-button type="primary" @click="getDataList(true)">
                        搜索
                      </a-button>
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
      </template>

      <template #bodyCell="{ text, record, index, column }"></template>
    </a-table>
  </a-drawer>
</template>

<script>
import {ref, toRefs, watch, reactive, computed} from "vue";
import request from "../../../../common/utils/request";
import store from "@/store";
import {Form} from "ant-design-vue";

const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
    uid: {
      type: [String, Number],
      default: 0,
    },
    tagId: {
      type: [String, Number],
      default: 0,
    },
    sourceType: {
      type: String,
      default: "channel",
    },
    isChannel: {
      type: Number,
      default: 0,
    },
  },
  setup(props, context) {
    const columns = [
      {
        title: "联系人",
        align: "center",
        dataIndex: "name",
        key: "name",
        fixed: store.getters.isMobile ? undefined : "left",
        width: 150,
      },
      {
        title: "公司名称",
        align: "center",
        dataIndex: "company",
        key: "company",
        customRender: ({text}) => {
          return text || "--";
        },
        width: 150,
      },
      {
        title: "成交率",
        align: "center",
        dataIndex: "deal_precent",
        key: "deal_precent",
        customRender: ({text}) => {
          return text + "%";
        },
        width: 100,
      },
      {
        title: "客户状态",
        align: "center",
        dataIndex: "status_txt",
        key: "status_txt",
        width: 150,
      },
      {
        title: "更新时间",
        align: "center",
        dataIndex: "updated_at",
        key: "updated_at",
        width: 180,
      },
      {
        title: "关联渠道",
        align: "center",
        dataIndex: "channel_name",
        key: "channel_name",
        customRender: ({text}) => {
          return text || "--";
        },
        width: 150,
      },
      {
        title: "客户预算",
        align: "center",
        dataIndex: "budget_amount",
        key: "budget_amount",
        customRender: ({text}) => {
          return text || text == 0 ? text + "元" : "--";
        },
        width: 150,
      },
      {
        title: "意向项目",
        align: "center",
        dataIndex: "village_name",
        key: "village_name",
        width: 150,
      },
      {
        title: "需求面积段",
        align: "center",
        dataIndex: "expect_area_max",
        key: "expect_area_max",
        customRender: ({text}) => {
          return text || text == 0 ? text + "m²" : "--";
        },
        width: 150,
      },
      {
        title: "预计签约时间",
        align: "center",
        dataIndex: "expect_contract",
        key: "expect_contract",
        customRender: ({text}) => {
          return text || "--";
        },
        width: 180,
      },
      {
        title: "备注",
        align: "center",
        dataIndex: "remark",
        key: "remark",
        width: 180,
      },
    ];

    const state = reactive({
      loading: false,
      villageOptions: [],
      customerStatusOptions: [],
      customerChannelOptions: [],
    });

    const searchParams = reactive({
      name: "", // 联系人名称
      tel: "", // 联系人电话
      company: "", // 公司名称
      village_id: undefined, // 意向项目id
      status: undefined, // 客户状态
      channel_id: undefined, // 客户渠道id
      created_time: undefined,
      created_start: undefined,
      created_end: undefined,
    });

    const {resetFields} = useForm(searchParams, {});

    const tableData = ref([]);

    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));

    const getDataList = (init = false) => {
      state.loading = true;
      if (init) {
        page.value = 1;
      }
      const params = {
        page: page.value,
        limit: limit.value,
        is_all: 1,
        type: "all"
      };
      if (props.sourceType == "user") {
        params.purpose_team_uid = props.uid;
      } else if (props.sourceType == "tag") {
        params.tag_id = props.tagId;
      } else {
        params.channel_id = props.id;
      }
      if (searchParams.created_time) {
        searchParams.created_start = searchParams.created_time[0];
        searchParams.created_end = searchParams.created_time[1];
      }
      if (props.isChannel == 1) {
        params.is_channel = 1;
      }
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }
      delete params.created_time;
      let url = "/business/customer/list";
      request
          .post("/org", url, params)
          .then((res) => {
            tableData.value = res?.list || [];
            total.value = res?.total || 0;
          })
          .finally(() => {
            state.loading = false;
          });
    };

    const getVillageList = () => {
      request
          .get("/org", "/build/villageAndBuildList/v2", {checked: 1})
          .then((res) => {
            let vList = [];
            res.villageList.forEach((item) => {
              vList.push({
                label: item.name,
                value: item.id,
              });
            });
            state.villageOptions = vList;
          });
    };

    const getStatus = () => {
      request.get("/org", "/business/customer/statusList", {}).then((res) => {
        state.customerStatusOptions = res.list.map((item) => ({
          value: item.status,
          label: item.name,
          ...item,
        }));
      });
    };

    const getChannelList = () => {
      request
          .get("/org", "/business/customer/channel/index", {})
          .then((res) => {
            state.customerChannelOptions = res.list.map((item) => {
              return {
                value: item.id,
                label: item.name,
              };
            });
          });
    };

    const init = () => {
      getVillageList();
      getStatus();
      getChannelList();
      getDataList(true);
    };

    const onClose = () => {
      context.emit("closeDetail");
    };

    const handleTableChange = (pager) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
      getDataList();
    };

    const handleRangePickerChange = (date, dateString) => {
      searchParams.created_time = date;
    };

    const reset = () => {
      resetFields();
      getDataList(true);
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          } else {
            resetFields();
          }
        }
    );
    return {
      ...toRefs(state),
      columns,
      tableData,
      onClose,
      searchParams,
      handleTableChange,
      pagination,
      dateFormatStr,
      getDataList,
      reset,
      handleRangePickerChange,
    };
  },
};
</script>

<style lang="less" scoped></style>
